package com.example.flowabledemo;

import org.flowable.engine.*;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.idm.api.Group;
import org.flowable.idm.api.User;
import org.flowable.task.api.Task;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
class FlowableCandicateGroupTest2 {

    @Autowired
    ProcessEngineConfiguration processEngineConfiguration;

    @Autowired
    RepositoryService repositoryService;

    @Autowired
    RuntimeService runtimeService;

    @Autowired
    TaskService taskService;

    @Autowired
    IdentityService identityService;

    @Test
    void createUser(){
        User user = identityService.newUser("张一");
        user.setFirstName("zhang");
        user.setLastName("yi");
        user.setEmail("zhangyi@qq.com");
        identityService.saveUser(user);

    }

    /**
     * 用户组的维护
     */
    @Test
    void createGroup(){
        Group group = identityService.newGroup("classone");
        group.setName("班级1");
        group.setType("c1");
        identityService.saveGroup(group);
    }

    @Test
    void bindGroupAndUser(){
        Group group = identityService.createGroupQuery().groupName("班级1").singleResult();
        List<User> list = identityService.createUserQuery().list();
        for (User user : list) {
            identityService.createMembership(user.getId(),group.getId());
        }
    }

    @Test
    void deployFlow(){

        Deployment deploy;
        deploy = repositoryService.createDeployment()
                .addClasspathResource("process/flowable_candicate_02.bpmn20.xml")
                .name("候选组 测试222")
                .deploy();
        System.out.println(deploy.getId());
    }

    @Test
    void startProcess(){
        String processInstanceId = "flowable_candicate_02_key:2:42ab4eea-18cd-11ef-8534-a08069abebfe";
        //创建流程实例的时候 放置变量  这个变量为全局变量
        ProcessInstance processInstance = runtimeService.startProcessInstanceById(processInstanceId);
        System.out.println(processInstance);
    }

    @Test
    void  claimGroupTask(){
        //用户 张飞登录之后 看是否有任务
        //先看他属于哪个group
        System.out.println("查询开始==============>");
        List<Group> list = identityService.createGroupQuery().groupMember("张一")
                .list();
        System.out.println("查询结束===========");
        for (Group group : list) {
            List<Task> list1 = taskService.createTaskQuery().taskCandidateGroup(group.getId())
                    .list();
            for (Task task : list1) {
                taskService.claim(task.getId(),"666");
                System.out.println("认领任务");
            }
        }
    }

    @Test
    void completeTask(){
        taskService.complete("8b7c9e8b-0f68-11ef-87c1-a08069abebfe");
    }


}
